package com.sky.service.impl;


import com.sky.service.KeysService;
import com.sky.utils.KeyStoreUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PublicKey;
import java.util.Base64;

/**
 * @author majun
 * @package com.sky.service.impl
 * @date 2024/11/20 16:58
 */
@Slf4j
@Service
public class KeysServiceImpl implements KeysService {

    @Autowired
    private KeyStoreUtil keyStoreUtil;

    /**
     * 获取用于前端加密的公钥
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public String getRsaPublicKey(String userId) throws Exception {

        // 检查用户密钥是否存在
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (FileInputStream fis = new FileInputStream("user-keystore.p12")) {
            keyStore.load(fis, "changeit".toCharArray());
        }

        if (!keyStore.containsAlias(userId)) {
            // 如果密钥对不存在，则生成并保存密钥对
            keyStoreUtil.generateAndSaveKeyPair(userId);
        }

        // 加载密钥对
        KeyPair keyPair = keyStoreUtil.loadKeyPair(userId);

        // 获取公钥并转换为 Base64 字符串
        PublicKey publicKey = keyPair.getPublic();
        String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKey.getEncoded());

        return publicKeyBase64;
    }

}
